#! /usr/bin/python
# -*- coding: utf-8 -*-
#######################################################################################
#                                                                                     #
#    File: daily_job.py                                                               #
#    Part of stage1st_cheater                                                         #
#    Home: http://stage1st-cheater.googlecode.com                                     #
#                                                                                     #
#    The MIT License                                                                  #
#                                                                                     #
#    Copyright (c) 2010-2011 <araya.akashic@gmail.com>                                #
#                                                                                     #
#    Permission is hereby granted, free of charge, to any person obtaining a copy     #
#    of this software and associated documentation files (the "Software"), to deal    #
#    in the Software without restriction, including without limitation the rights     #
#    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell        #
#    copies of the Software, and to permit persons to whom the Software is            #
#    furnished to do so, subject to the following conditions:                         #
#                                                                                     #
#    The above copyright notice and this permission notice shall be included in       #
#    all copies or substantial portions of the Software.                              #
#                                                                                     #
#    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR       #
#    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,         #
#    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE      #
#    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER           #
#    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,    #
#    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN        #
#    THE SOFTWARE.                                                                    #
#                                                                                     #
#######################################################################################
# This code is to automatically apply job and get job reward for stage1st bbs

# Author: Araya

import time

import urllib
import urllib2

from browser_bogus import Browser

#customized these
#adding account as "username":"password"
account_list = {"":""}
#total attempts
cycle = 1
#wait 1 hr 10 s before each attempt
delay = 3610 * 22

#do not change below this
siteurl = "http://bbs.saraba1st.com/2b"
index_page = "/index.php"
login_page = "/login.php"
job_page = "/jobcenter.php"

job_list = "list"
job_applied = "applied"
job_apply = "apply"
job_gain = "gain"

user_agent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.772.0 Safari/535.1"

#submit data tail
data_tail = ""
        
class ExamNotAvailable(Exception):
    def __init__(self, time):
        self.value = time
        
    def __str__(self):
        return repr(self.value)
    
class LoginFailed(Exception):
    def __init__(self, str):
        self.value = str
        
    def __str__(self):
        return repr(self.value)
    

#method login
def login(user):
    logindata = {"forward":"",
                 "jumpurl":siteurl+index_page,
                 "step":"2",
                 "lgt":"0",
                 "pwuser":user.username,
                 "pwpwd":user.password,
                 "hideid":"0",
                 "cktime":"0",
                 "submit":""}
    
    en_logindata = urllib.urlencode(logindata)
    
    url = siteurl + login_page
    request = urllib2.Request(url)
    request.add_header("User-Agent", user.user_agent)
    result = user.urlOpener.open(request)
    #print "Getting login page"
    url = url + "?"
    request = urllib2.Request(url, en_logindata)
    request.add_header("User-Agent", user.user_agent)
    result = user.urlOpener.open(request)
    if result.read().find("http-equiv=\"refresh\"") < 0:
        raise LoginFailed(user.username)
    else:
        print "Daily Job Login %s" % user.username
#    print user.cookie
    
def cheat(user):
    uridata = {"action":job_list
               }
    
    en_uridata = urllib.urlencode(uridata)
#    print en_uridata
    print "Getting job center"
    url = siteurl + job_page + "?" + en_uridata
    request = urllib2.Request(url)
    request.add_header("User-Agent", user.user_agent)
    result = user.urlOpener.open(request)
    
    
    pagelines = result.readlines()
#    #print len(pagelines)
#    #extracting logout URI
#    line = pagelines[74]
#    user.logout_URI = line.split("=\"")[-1].split("\"")[0]
    for line in pagelines:
        if line.find(login_page) >= 0:
            user.logout_URI = line.split("=\"")[-1].split("\"")[0]
            
        if line.find("verifyhash") >= 0:
            user.verifyhash = line.split("\'")[1]
#            print "verifyhash=" + user.verifyhash
            
    #apply job
    uridata1 = {"action":job_apply,
               "verify":user.verifyhash,
               "nowtime":int(time.time() * 1000)
               }
    uridata2 = {"verify":user.verifyhash}
    
    en_uridata = urllib.urlencode(uridata1) +  "&" + urllib.urlencode(uridata2)

    submitdata = {"id":5,
                  "step":2}
    en_submitdata = urllib.urlencode(submitdata)
    
    url = siteurl + job_page + "?" + en_uridata
    request = urllib2.Request(url, en_submitdata)
    request.add_header("User-Agent", user.user_agent)
    result = user.urlOpener.open(request)
    if len(result.read()) <= 144:
        raise ExamNotAvailable(-1)
    print "Job applied"
    
    #get job reward
    uridata1 = {"action":job_gain,
               "verify":user.verifyhash,
               "nowtime":int(time.time() * 1000)
               }
    uridata2 = {"verify":user.verifyhash}
    
    en_uridata = urllib.urlencode(uridata1) +  "&" + urllib.urlencode(uridata2)

    submitdata = {"id":5,
                  "step":2}
    en_submitdata = urllib.urlencode(submitdata)
    
    url = siteurl + job_page + "?" + en_uridata
    request = urllib2.Request(url, en_submitdata)
    request.add_header("User-Agent", user.user_agent)
    result = user.urlOpener.open(request)
    print "Job reward got"
    
    return 1
#    result_data = result.read()
#    return result_data.find("+1")

    
    
def logout(user):
    url = siteurl + "/" + user.logout_URI
    request = urllib2.Request(url)
    request.add_header("User-Agent", user.user_agent)
    result = user.urlOpener.open(request)
    print "Daily Job Logout " + user.username
    
def perform_cheating():
    for n, p in account_list.iteritems():
        user = Browser(n, p, user_agent)
        submit_success = -1
        try:
            try:
                login(user)
            except urllib2.URLError:
                print "Failed to connect to host. Please check your Internet connection"
            except LoginFailed:
                print "Daily Job Login Failed for %s" % user.username
            while submit_success < 0:
                try:
                    submit_success = cheat(user)
                except urllib2.URLError:
                    print "Failed to connect to host. Please check your Internet connection"
                except ExamNotAvailable:
                    print "Daily job is not available for %s: Already done" % user.username
                    break
                #print submit_success
            logout(user)
        except:
            pass
        
def _perform_cheating(browser):
    submit_success = -1
    try:
        login(browser)
        while submit_success < 0:
            try:
                submit_success = cheat(browser)
            except ExamNotAvailable:
                print "Daily job is not available for %s: Already done" % browser.username
                break
            #print submit_success
        logout(browser)
    except urllib2.URLError:
                print "Failed to connect to host. Please check your Internet connection"
    except LoginFailed:
                print "Daily Job Login Failed for %s" % browser.username
    except:
        pass
    
if __name__ == "__main__":
    while cycle:
        print "------------------------------------------"
        print time.strftime("%a, %b %d %Y %H:%M:%S", time.localtime()) + "-----------------"
        perform_cheating()
        if cycle > 1:
            time.sleep(delay)
        cycle = cycle - 1